package player

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/advert"
	"GameServer/Game/errors"
	"GameServer/Game/lib"
	"GameServer/Game/m"
	"GameServer/Game/sp"
)

func (p *Player) AdRewardsInfoRequest(req *sp.AdRewardsInfoRequest) (res *sp.AdRewardsInfoResponse) {
	adRewards := p.User.GetAdRewards()
	res = &sp.AdRewardsInfoResponse{
		List: lib.FormatAdRewardSps(adRewards.Rewards),
	}
	return
}

// 广告获取奖励 9031
func (p *Player) AdRewardsReceiveRequest(req *sp.AdRewardsReceiveRequest) (res *sp.AdRewardsReceiveResponse, err error) {
	us := p.User
	switch req.Typ {
	case 1:
		advert.Module.AddAdCnt(data.AdTurntable)                         // 统计转盘广告
		advert.Module.AddAdUser(us.Uid.Hex(), us.Name, data.AdTurntable) // 统计转盘广告
	case 2:
		advert.Module.AddAdCnt(data.AdEnergy)                         // 统计体力广告
		advert.Module.AddAdUser(us.Uid.Hex(), us.Name, data.AdEnergy) // 统计体力广告
	case 3:
		advert.Module.AddAdCnt(data.AdGold)                         // 统计金币广告
		advert.Module.AddAdUser(us.Uid.Hex(), us.Name, data.AdGold) // 统计金币广告
	case 4:
		advert.Module.AddAdCnt(data.AdAltar)                         // 统计祭坛广告
		advert.Module.AddAdUser(us.Uid.Hex(), us.Name, data.AdAltar) // 统计祭坛广告
	}

	// 成就，记录观看广告
	lib.AddAchievProgress(us, data.AchievementType.Watch_ads, 1)

	f := func(typ int64) (rAdReward *m.AdReward, uProp *m.UpdateProp, resGoodsList []*m.Goods, boxResList []*m.BoxRes, err error) {
		switch req.Typ {
		case 1:
			return lib.GiveAdDailyRewards("AdRewardsReceiveRequest", p.User, p.Send)
		case 2:
			return lib.GiveAdEnergyRewards("AdRewardsReceiveRequest", p.User, p.Send)
		case 3:
			return lib.GiveAdGoldRewards("AdRewardsReceiveRequest", p.User, p.Send)
		default:
			err = errors.New("无效的广告类型")
		}
		return
	}
	// 祭坛奖励
	if req.Typ == 4 {
		rAdReward, err := lib.GiveAdAltarRewards(p.User)
		if err != nil {
			res = &sp.AdRewardsReceiveResponse{
				Errcode: errors.ErrCode(err),
			}
			return res, err
		}

		res = &sp.AdRewardsReceiveResponse{
			AdInfo: lib.FormatAdRewardSp(rAdReward),
		}
		return res, nil
	}

	rAdReward, uProp, resGoodsList, boxResList, err := f(req.Typ)
	if err != nil {
		res = &sp.AdRewardsReceiveResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	// 有成就完成，进行通知
	achLst := lib.AchievComplete(p.User)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}
	res = &sp.AdRewardsReceiveResponse{
		AdInfo: lib.FormatAdRewardSp(rAdReward),
		Res:    lib.FormatGoodsInfoSps(resGoodsList),
		BoxRes: lib.FormatBoxResSps(boxResList),
	}

	if uProp != nil {
		p.TimelyUpdateProp(req.GetType(), uProp)
		utils.AsyncFunc(func() {
			p.UpdateProp(req.GetType(), uProp)
		})
	}
	return
}
